import {getComment,getCommentAns} from "@/api/comment";
import {addLike,addLikeAns,disLike,disLikeAns} from "@/api/comment";
interface IState {
    commentList: Array<IList | never>
}
export interface IList {
    aId: string;
    atime: number;
    content: string;
    countLike?: Array<string>;
    userActionId: string;
    userInfo: {
        avatar: string;
        userEmail: string;
        userId: string;
        userName: string
    }
}
const state: IState = {
    commentList: []
}
const mutations = {
    getCommentInfo(state: IState,payload: any) {
        state.commentList = payload
    },
    userAddLike(state: IState, payload: any) {
        for(let item of state.commentList){
            if(item.aId === payload.aId){
                item.countLike?.push(payload.data)
            }
        }
    },
    userDisLike(state: IState,payload: any) {
        for(let item of state.commentList){
            if(item.aId === payload.aId){
                const index = item.countLike?.findIndex(item => item === payload.data)
                if(index !== -1)
                    item.countLike?.splice((index as number),1)
            }
        }
    }
}
const actions = {
    getCommentInfo(context: any){
        getComment()
            .then(res => {
                const {code,msg,data} = res as unknown as getCommentAns
                if(code === 200){
                    context.commit('getCommentInfo',data)
                }else{
                    console.log(msg)
                }
            })
    },
    userAddLike(context: any,aId: string){
        addLike(aId)
            .then(res => {
                const {code,msg,data} = res as unknown as addLikeAns
                if(code === 200){
                    context.commit('userAddLike',{
                        aId,
                        data
                    })
                }else{
                    console.log(msg)
                }
            })
    },
    userDisLike(context: any,aId: string){
        disLike(aId)
            .then(res => {
                const {code,msg,data} = res as unknown as disLikeAns
                if(code === 200){
                    context.commit('userDisLike',{
                        aId,
                        data
                    })
                }else{
                    console.log(msg)
                }
            })
    }

}
export default {
    namespaced: true,
    state,
    mutations,
    actions
}